﻿using MoetutuServer.Helper;
using MoetutuServer.PublishHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace MoetutuServer.WebSite.Konachan
{
    class ScannerKonachan
    {
        public static void Start()
        {

            string url = "https://konachan.net/post.xml?limit=30&page=5";
            string json = GetJson(url);
            if (json != "")
                AnalysisJson(json);

        }


        private static string GetJson(string url)
        {
            String SHtml = Helper.WebHelper.HttpGet(url);
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(SHtml);

                string jsonText = Regex.Replace(JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None), "(?<=\")(@)(?!.*\":\\s )", string.Empty, RegexOptions.IgnoreCase);
                jsonText = Regex.Replace(jsonText, @"\?xml", "xml");
                return jsonText;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return "";
            }
        }
        private static void AnalysisJson(string json)
        {
            JsonKonachan.Root AllJson = JsonConvert.DeserializeObject<JsonKonachan.Root>(json);
            List<JsonKonachan.PostItem> list = AllJson.posts.post;
            foreach (JsonKonachan.PostItem Single in list)
            {
                Console.WriteLine(Single.rating);
                if (Single.rating != "s")
                    continue;
                if (Single.score < 50) {
                    Console.WriteLine("Konachan评分过低，需要跳过");
                    continue;
                }
                if (StaticValue.OldImgID1.Contains(Single.id))
                {
                    Console.WriteLine(Single.id + "已发布过，跳过");
                    continue;//如果存在直接跳过
                }
                Console.WriteLine(Single.id);
                Console.WriteLine(Single.file_url);
                Console.WriteLine(Single.preview_url);

                
                bool PublishFlag = ArticleHelper.CreateContent("https:" + Single.file_url, "https:" + Single.preview_url, Single.tags, Single.source);
                if (PublishFlag)
                {
                    FileHelper.AppendUTF8Text(StaticValue.OldImgIdPath, Single.id);
                    StaticValue.OldImgID1.Add(Single.id);
                }


            }

        }

    }
}
